<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>04.列表排序</title>
  </head>
  <style>
    ul {
      list-style-type: disc;
    }
  </style>

  <body>
    <div id="app">
      <ul>
        <h1>{{message}}</h1>
        <input type="text" placeholder="请输入姓名" v-model="keyWord">
        <button @click="sortType=1">年龄升序</button>
        <button @click="sortType=2">年龄降序</button>
        <button @click="sortType=0">原来排序</button>
        <h2>{{keyWord}}</h2>
        <li v-for="(item,index) in newArr" :key="index">{{item}}</li>
      </ul>
    </div>
  </body>
  <script src="../js/vue.js"></script>
  <script type="text/javascript">
    const vm = new Vue({
      el: "#app",
      data: {
        message: "对象列表展示",
        keyWord: '', //关键字
        sortType: 0, //排序方式 0原顺序 1升序 2降序
        arr: [{
            name: '马冬梅',
            age: 89,
            gender: 'female'
          },
          {
            name: '周冬雨',
            age: 25,
            gender: 'female'
          },
          {
            name: '周杰伦',
            age: 136,
            gender: 'male'
          },
          {
            name: '桂伦镁',
            age: 39,
            gender: 'female'
          },
        ],
      },
      computed: {
        // 使用计算属性创建你一个新的数组和原来的数组独立存在， 互相不影响
        newArr: function () {
          const {
            keyWord,
            arr,
            sortType
          } = this;
          //1.过滤
          let newArr = arr.filter((item, index) => {
            return item.name.indexOf(keyWord) !== -1
          })
          //2.排序
          if (sortType) {
            newArr.sort((a, b) => {
              if (sortType === 1) {
                return a.age - b.age
              } else {
                return b.age - a.age
              }
            })
          }
          return newArr
        }
      }
    })
  </script>

</html>